<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use app\common\lib\Show;
use think\facade\View;
use think\facade\Request;
use app\admin\business\AdminUser;

class Login extends BaseController
{
    /**
     * 登录页
     *
     * @return \think\Response
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 用户信息校对
     *
     * @return \think\response\Json
     */
    public function check()
    {
        // 判断提交方法是否为 POST
        if (!Request::isPost()) {
            return Show::error('非法请求');
        }

        // 获取提交数据
        $data = [
            'username' => Request::param('username', '', 'trim'),
            'password' => Request::param('password', '', 'trim'),
            'captcha'  => Request::param('captcha', '', 'trim')
        ];

        // 用户信息验证
        $validate = new \app\admin\validate\AdminUser();
        if (!$validate->check($data)) {
            return Show::error($validate->getError());
        }

        try{
            $adminUser = new AdminUser();
            $result = $adminUser->login($data);
        } catch (\Exception $e) {
            return Show::error($e->getMessage());
        }
        return $result ? Show::success([], '登陆成功') : Show::error('登陆失败');
    }
}
